<?php
namespace Plu\Library\Validation\Validator;

use Phalcon\Validation,
	Phalcon\Validation\Message,
	Phalcon\Validation\Validator;

class IdCard extends Validator {
	public function validate(Validation $validator, $attribute) {
		$value = $validator->getValue($attribute);

		if (strlen($value) != 18) {
			$validator->appendMessage(new Message("传入的身份证长度不正确", $attribute, 'IdCard'));
			return false;
		}

		$value = str_split($value);
		$check_code = strtoupper(array_pop($value));
		$id = array_reverse($value);
		$sum = 0;
		foreach ($id as $k => $v) {
			$w = pow(2, $k + 1) % 11;
			$sum += $v * $w;
		}

		$isValidation = str_replace(10, 'X', (12 - $sum % 11) % 11) == $check_code;

		if ($isValidation) {
			return true;
		} else {
			$validator->appendMessage(new Message("传入的身份证不合法", $attribute, 'IdCard'));
			return false;
		}
	}
}
?>
